<template>
  <div>
    <van-nav-bar title="登录/注册" />
    <van-form @submit="onSubmit">
      <van-field required v-model="mobile" name="mobile" label="手机号" placeholder="请输入11位手机号"
        :rules="[{ pattern: pattern, required: true, message: '请填写正确格式的手机号' }]" maxlength="11" />
      <van-field required v-model="code" type="code" name="code" label="短信验证码" placeholder="短信验证码"
        :rules="[{ pattern: pattern2, required: true, message: '请填写正确格式的验证码' }]" maxlength="6" />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit" :disabled="disabled" :loading="isloading"
          loading-text="正在登录中...">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import Notify from '@/ui/Notify'
export default {
  data () {
    return {
      mobile: '13777777777',
      // 默认246810
      code: '246810',
      pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
      pattern2: /^\d{6}$/,
      disabled: false,
      isloading: false
    }
  },
  created () {
    this.disabled = false
  },
  methods: {
    // 通过验证才会触发
    async onSubmit (values) {
      this.isloading = true
      // 使用try捕获错误
      try {
        const { data: res } = await this.$api.loginAPI(values)
        Notify({ type: 'success', message: res.message })
        this.$storage.setStorage('geek-itheima', res.data.token)
        this.$storage.setStorage('refresh_token', res.data.refresh_token)
        // 获取查询参数,然后跳回进入的页面
        console.log(this.$route.query.path)
        this.$router.replace({
          path: `${this.$route.query.path}`
        })
      } catch (error) {
        Notify({ type: 'danger', message: error.code })
      }
      this.isloading = false
    }
  }
}
</script>

<style lang="less" scoped>
</style>
